
//
//  EmoticonViewModel.swift
//  表情键盘
//
//  Created by 孙明海 on 16/2/17.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import UIKit

/**
 1. emoticons.plist 定义表情包数组
 packages 字典数组中，每一个 id 对应不同表情包的目录
 2. 从 每一个表情包目录中，加载 info.plist 可以获得不同的表情内容
 id	目录名
 group_name_cn	表情分组名称- 显示在 toolbar 上
 emoticons	 数组
 字典
 chs		发送给服务器的字符串
 png		在本地显示的图片名称
 code	emoji 的字符串编码
 
 */
/// 表情包视图模型
class EmoticonManager {
    /// 单例
    static let sharedManager = EmoticonManager()
    
    
    // MARK: - 生成属性字符串
    /// 将字符串转换成属性字符串
    func emotionText(str: String, font: UIFont) -> NSAttributedString {
        let mStr = NSMutableAttributedString(string: str)
        
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let results = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        var count = results.count
        
        while count > 0 {
            let range = results[--count].rangeAtIndex(0)
            let emStr = (str as NSString).substringWithRange(range)
            if let emotion = emotionWithString(emStr) {
                let imageText = EmoticonAttachment(emoticon: emotion).imageText(font)
                mStr.replaceCharactersInRange(range, withAttributedString: imageText)
            }
        }
        
        return mStr
    }
    
    private func emotionWithString(str: String) -> Emoticon? {
        for package in packages {
            if let emotion = package.emoticons.filter({$0.chs == str}).first {
                return emotion
            }
        }
        return nil
    }

    
    /// 表情包
    lazy var packages = [EmoticonPackage]()
    
    // MARK: - 最近表情
    func addFavorite(emoticon: Emoticon) {
        emoticon.times++
        if !packages[0].emoticons.contains(emoticon) {
            packages[0].emoticons.insert(emoticon, atIndex: 0)
            packages[0].emoticons.removeAtIndex(packages[0].emoticons.count - 2)
        }
        packages[0].emoticons.sortInPlace {$0.times > $1.times}
        
    }
    
    /// 构造函数
    init() {
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
        let array = (dict["packages"] as! NSArray).valueForKey("id")
        packages.append(EmoticonPackage(dict: ["group_name_cn": "最近"]))
        
        for id in array as! [String] {
            loadInfoPlist(id)
        }
    }
    /// 加载表情包
    ///
    /// - parameter id: 表情包路径
    private func loadInfoPlist(id: String) {
        print(id)
        let path = NSBundle.mainBundle().pathForResource("info.plist", ofType: nil, inDirectory: "Emoticons.bundle/\(id)")!
        let dict = NSDictionary(contentsOfFile: path) as! [String: AnyObject]
        packages.append(EmoticonPackage(dict: dict))
    }
}